package base.utils;

import android.util.Log;

public class ApkDownloadUtil {
    private volatile static ApkDownloadUtil mApkDownloadUtil = null;
    private DownLoadListenner mDownLoadListenner;
    public boolean isStart=false;
    private ApkDownloadUtil() {
    }
    public static ApkDownloadUtil getInstance() {
        if (mApkDownloadUtil == null) {
            synchronized (ApkDownloadUtil.class) {
                if (mApkDownloadUtil == null) {
                    mApkDownloadUtil = new ApkDownloadUtil();
                }
            }
        }
        return mApkDownloadUtil;
    }

    public void startDownload(String url){
        if(isStart)return;
        isStart=true;
        DownloadManager.getInstance().download(url, new DownLoadObserver() {
            @Override
            public void _onNext(DownloadInfo downloadInfo) {
                long l = downloadInfo.getProgress() * 100 / downloadInfo.getTotal();
                Log.e("DownloadManager", "next:" + downloadInfo.getProgress() + "  " + downloadInfo.getTotal() + " = " + (downloadInfo.getTotal() - downloadInfo.getProgress()));
                if(mDownLoadListenner!=null){
                    mDownLoadListenner.onDownloading(l);
                }
            }

            @Override
            public void onError(Throwable e) {
                Log.e("DownloadManager", "error:" + e.getMessage());
                if(mDownLoadListenner!=null){
                    mDownLoadListenner.onError(e.getMessage());
                }
                isStart=false;
                DownloadManager.getInstance().cancel(url);
            }

            @Override
            public void onComplete() {
                Log.e("DownloadManager", "onComplete:");
                if(mDownLoadListenner!=null){
                    mDownLoadListenner.onComplete(downloadInfo);
                }
                isStart=false;
            }
        });
    }

    public void setDownLoadFile(String path){
        DownloadManager.getInstance().setDownLoadFile(path);
    }

    public interface DownLoadListenner {
        public void onComplete(DownloadInfo downloadInfo);
        public void onDownloading(long progress);
        public void onError(String error);
    }
    public void setDownLoadListener(DownLoadListenner downLoadListener){
        mDownLoadListenner=downLoadListener;
    }
}
